package vikaa.ui;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import vikaa.timelinepackage.AsyLoadImg;
import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.tools.StringUtils;
import vikaa.tools.ValueClass;
import vikaa.wowo.R;
import vikaa.wowo.cache.AuthoSharePreference;
import vikaa.wowo.cache.DefaultValueSharePreference;
import vikaa.wowo.cache.UserInfoSharePreference;

public class SettingsUser extends Activity implements OnFocusChangeListener , OnClickListener{
	private static final String TAG = "SettingsUser";
	private EditText nameEdt;
	private EditText phoneEdt;
	private EditText emailEdt;
	private ImageView avaterImg;
	private LinearLayout backBtn;
	private RelativeLayout feedbackBtn;
	private RelativeLayout aboutusBtn;
	private ImageView logouBtn;
	
	private String phone;
	private String nickname;
	private String email;
	private String phone_validate;
	private String email_validate;
	
	private long codetime = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.settings_user);
		initview();
	}
	private void initview(){
		nameEdt = (EditText)findViewById(R.id.nameTv);
		nameEdt.setOnFocusChangeListener(this);
		nameEdt.addTextChangedListener(mNicknameWatcher);
		phoneEdt = (EditText)findViewById(R.id.phoneTv);
		phoneEdt.setOnFocusChangeListener(this);
		phoneEdt.addTextChangedListener(mPhoneWatcher);
		emailEdt = (EditText)findViewById(R.id.emailTv);
		emailEdt.setOnFocusChangeListener(this);
		emailEdt.addTextChangedListener(mEmailWatcher);
		avaterImg = (ImageView)findViewById(R.id.avaterImg);
		backBtn = (LinearLayout)findViewById(R.id.backBtn);
		feedbackBtn = (RelativeLayout)findViewById(R.id.feedbackRl);
		aboutusBtn = (RelativeLayout)findViewById(R.id.aboutusRl);
		logouBtn = (ImageView)findViewById(R.id.logoutBtn);
		nickname = UserInfoSharePreference.getNickname(getApplicationContext());
		phone = UserInfoSharePreference.getPhone(getApplicationContext());
		email = UserInfoSharePreference.getEmail(getApplicationContext());
		nameEdt.setText(nickname);
		phoneEdt.setText(phone);
		emailEdt.setText(email);
		AsyLoadImg.loadCornerAvater(UserInfoSharePreference.getAvater(getApplicationContext()), avaterImg,ValueClass.CORNER_PIXEL);
		RelativeLayout nameRl = (RelativeLayout)findViewById(R.id.nameRl);
		nameRl.setOnFocusChangeListener(this);
		LinearLayout scv = (LinearLayout)findViewById(R.id.scv);
		scv.setOnClickListener(this);
		avaterImg.setOnClickListener(this);
		feedbackBtn.setOnClickListener(this);
		aboutusBtn.setOnClickListener(this);
		logouBtn.setOnClickListener(this);
		backBtn.setOnClickListener(this);
	}
	public void onFocusChange(View v, boolean hasFocus) {
		switch(v.getId()){
		case R.id.nameTv:
			if(hasFocus){
			}
			else{
				String value = nameEdt.getText().toString();
				if(!(value.equals(nickname))){
					new UpdateSettingsThread("nickname", value).start();
				}
			}
			break;
		case R.id.phoneTv:
			if(hasFocus){
			}
			else{
				String value = StringUtils.spaceEdit(phoneEdt.getText().toString());
				if(StringUtils.isMobileNO(value)){
					if(!(value.equals(phone))) {
						new UpdateSettingsThread("phone", value).start();
					}
				}else {
					Toast toast = new Toast(SettingsUser.this);
                	toast = Toast.makeText(getApplicationContext(), getString(R.string.active_phone_msg5), Toast.LENGTH_SHORT);
                	toast.setGravity(Gravity.CENTER, 0, 0);
                	toast.show();
					phoneEdt.setText(phone);
				}
			}
			break;
		case R.id.emailTv:
			if(hasFocus){
			}
			else{
				String value = StringUtils.spaceEdit(emailEdt.getText().toString());
				if(StringUtils.isEmail(value)){
					if(!(value.equals(email))){
						new UpdateSettingsThread("email", value).start();
					}
				}else {
					//Toast.makeText(getApplicationContext(), getString(R.string.email_msg), Toast.LENGTH_SHORT).show();
					emailEdt.setText(email);
				}
			}
			break;
		}
	}
	TextWatcher mNicknameWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
            temp = s;
        }
       
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
        }
       
        public void afterTextChanged(Editable s) {
            editStart = nameEdt.getSelectionStart();
            editEnd = nameEdt.getSelectionEnd();
            if (temp.length() > 16) {
                s.delete(editStart-1, editEnd);
                int tempSelection = editStart;
                nameEdt.setText(s);
                nameEdt.setSelection(tempSelection);
            }
          
        }
    };
	TextWatcher mPhoneWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
            temp = s;
        }
       
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
        }
       
        public void afterTextChanged(Editable s) {
            editStart = phoneEdt.getSelectionStart();
            editEnd = phoneEdt.getSelectionEnd();
            if (temp.length() > 11) {
                s.delete(editStart-1, editEnd);
                int tempSelection = editStart;
                phoneEdt.setText(s);
                phoneEdt.setSelection(tempSelection);
            }
            /*if(temp.length() == 11){
            	if(!TextUtil.isMobileNO((phoneEdt.getText().toString()))){
            		Toast toast = new Toast(SettingsUser.this);
                	toast = Toast.makeText(getApplicationContext(), getString(R.string.active_phone_msg5), Toast.LENGTH_SHORT);
                	toast.setGravity(Gravity.CENTER, 0, 0);
                	toast.show();
            		phoneEdt.setText(phone);
            	}
            }*/
        }
    };
    TextWatcher mEmailWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
            temp = s;
        }
       
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
        }
       
        public void afterTextChanged(Editable s) {
            editStart = emailEdt.getSelectionStart();
            editEnd = emailEdt.getSelectionEnd();
            if (temp.length() > 30) {
                s.delete(editStart-1, editEnd);
                int tempSelection = editStart;
                emailEdt.setText(s);
                emailEdt.setSelection(tempSelection);
            }
            if(temp.length() == 30){
            	if(!StringUtils.isEmail((emailEdt.getText().toString()))){
            		//Toast.makeText(SettingsUser.this,getString(R.string.email_msg), Toast.LENGTH_SHORT).show();
            		emailEdt.setText(email);
            	}
            }
        }
    };
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if(ev.getAction() == MotionEvent.ACTION_MOVE){
			nameEdt.clearFocus();
			phoneEdt.clearFocus();
			emailEdt.clearFocus();
			DialogService.hideSoftKeypad(SettingsUser.this);
		}
		return super.dispatchTouchEvent(ev);
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case 1:
			final EditText input = new EditText(this);
			return new AlertDialog.Builder(this)
			.setTitle(getString(R.string.active_phone_msg3))
			.setView(input)
			.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					DialogService.hideSoftKeypad(SettingsUser.this);
					String code = input.getText().toString();
					String phone = phoneEdt.getText().toString();
					new ActiveThread(phone, "", code).start();
				}
			})
			.setNegativeButton(R.string.cancel, null).create();
		default:
			return null;
		}
	}
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.scv:
			nameEdt.clearFocus();
			phoneEdt.clearFocus();
			emailEdt.clearFocus();
			DialogService.hideSoftKeypad(SettingsUser.this);
			break;
		case R.id.arrawImg:
			break;
		case R.id.feedbackRl:
			startActivity(new Intent(SettingsUser.this,Feedback.class));
			break;
		case R.id.aboutusRl:
			startActivity(new Intent(SettingsUser.this,AboutUs.class));
			break;
		case R.id.logoutBtn:
			AuthoSharePreference.putToken(SettingsUser.this, "");
			AuthoSharePreference.putUid(SettingsUser.this, "");
			AuthoSharePreference.putCookie(SettingsUser.this, "");
			Mywowo.crashflag = true;
			DefaultValueSharePreference.putLoginFlag(SettingsUser.this, false);
			DefaultValueSharePreference.putCheckNew(SettingsUser.this, true);
			//Intent i = new Intent(SettingsUser.this,LookAround.class);
			//startActivity(i);
			finish();
			break;
		case R.id.backBtn:
			finish();
			break;
		}
	}
    Handler mhandler = new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case 1:
				if(!phone_validate.equals("1")){
					phoneEdt.setText("待验证");
					new GetCodeThread(phone).start();
				}
				break;
			case 2:
				showDialog(1);
				break;
			case 3:
				if(msg.obj != null){
					Toast.makeText(SettingsUser.this, (String)msg.obj, Toast.LENGTH_SHORT).show();
				}
				else
					Toast.makeText(SettingsUser.this, R.string.server_crash, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				Toast.makeText(SettingsUser.this, R.string.network_crash, Toast.LENGTH_SHORT).show();
				break;
			case 5:
				phoneEdt.setText(phone);
				break;
			}
		}
    };
	class UpdateSettingsThread extends Thread{
		private String value;
		private String key;
		private boolean isrun = true;
		private UpdateSettingsThread(String key,String value){
			this.value = value;
			this.key = key;
		}
		@Override
		public void run() {
			while(isrun){
				isrun = false;
				try{
					Map<String,String> map = new HashMap<String, String>() ;
					map.put(key, value);
					JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(HttpUtil.BASE_URL+"user/edit", map));
					if(jsonObj.getString("result").equals("1")){
						UserInfoSharePreference.putNickname(SettingsUser.this, jsonObj.getJSONObject("info").getString("nickname"));
						UserInfoSharePreference.putAvater(SettingsUser.this, jsonObj.getJSONObject("info").getString("avatar"));
						UserInfoSharePreference.putEmail(SettingsUser.this, jsonObj.getJSONObject("info").getString("email"));
						UserInfoSharePreference.putPhone(SettingsUser.this, jsonObj.getJSONObject("info").getString("phone"));
						phone = jsonObj.getJSONObject("info").getString("phone");
						email = jsonObj.getJSONObject("info").getString("email");
						nickname = jsonObj.getJSONObject("info").getString("nickname");
						phone_validate = jsonObj.getJSONObject("info").getString("phone_validate");
						email_validate = jsonObj.getJSONObject("info").getString("email_validate");
						Message msg = mhandler.obtainMessage(1);
						msg.sendToTarget();						
					}
					else if (jsonObj.getString("result").equals("0")){
						Message msg = mhandler.obtainMessage(3);
						msg.obj = jsonObj.getString("msg");
						msg.sendToTarget();
					}else{
						Message msg = mhandler.obtainMessage(4);
						msg.sendToTarget();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	class GetCodeThread extends Thread{
		private String phone;
		public GetCodeThread(String phone) {
			super();
			this.phone = phone;
		}
		@Override
		public void run() {
			Map<String, String> map = new HashMap<String, String>();
			map.put("phone", phone);
			String url = HttpUtil.BASE_URL + "user/validataphone";
			try {
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				if(jsonObj.getString("result").equals("1")){
					codetime = Long.valueOf(jsonObj.getString("info"));
					Message msg = mhandler.obtainMessage(2);
					msg.obj = codetime;
					mhandler.sendMessage(msg);
				}
				else if(jsonObj.getString("result").equals("2")){
					String error = jsonObj.getJSONObject("info").getString("error");
					Message msg = mhandler.obtainMessage(4);
					msg.obj = error;
					mhandler.sendMessage(msg);
				}
				else{
					Message msg = mhandler.obtainMessage(3);
					msg.obj = jsonObj.getString("msg");
					mhandler.sendMessage(msg);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class ActiveThread extends Thread{
		private String phone;
		private String password;
		private String code;
		public ActiveThread(String phone, String password, String code) {
			super();
			this.phone = phone;
			this.password = password;
			this.code = code;
		}
		@Override
		public void run() {
			Map<String, String> map = new HashMap<String, String>();
			map.put("phone", phone);
			map.put("password", password);
			map.put("code", code);
			String url = HttpUtil.BASE_URL + "user/activephone";
			try {
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				if(jsonObj.getString("result").equals("1")){
					Message msg = mhandler.obtainMessage(5);
					mhandler.sendMessage(msg);
				}
				else if(jsonObj.getString("result").equals("2")){
					Message msg = mhandler.obtainMessage(4);
					msg.obj = jsonObj.getJSONObject("info").getString("error");
					mhandler.sendMessage(msg);
				}
				else{
					Message msg = mhandler.obtainMessage(3);
					msg.obj = jsonObj.getString("msg");
					mhandler.sendMessage(msg);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
